<?php
namespace Common\Model;
use Common\Controller\AdminbaseController;
use Common\Model\VRLiveModel;
use Think\Cache\Driver\Redis;

class LiveModel extends VRLiveModel
{
	
	protected $_validate = array(
		//array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间)
		//array('offer_price', 'require', '出价不能为空！', 0, 'regex', CommonModel:: MODEL_BOTH  ),
	);

	public function queryLiveList($status = -1, $name = null, $category = -1, $pageStart, $pageSize){
		$where = array();
		$where['is_fast'] = array('EQ', 0); //非快直播
		if(-1 != $status){
			//状态 1 正常 0 删除 2 直播结束 3 未开始 4 正在直播 5 直播回顾
			if(3 == $status){
				$where['status'] = array('EQ', 1);
				$where['start_time'] = array('GT', date('Y-m-d H:i:s'));
			}else if(2 == $status){
				$where['status'] = array('EQ', 2);
			}else if(4 == $status){
				$where['status'] = array('IN', array('1', '4'));
				$where['start_time'] = array('ELT', date('Y-m-d H:i:s'));
			}else if(5 == $status){
				$where['status'] = array('EQ', 5);
			}
		}else {
			//2 为删除
			$where['status'] = array('NEQ', 0);
		}
		if($name && !empty($name)){
			$where['name'] = array('like','%'.$name.'%');
		}
		$where['category'] = array('NEQ', 6);
		if(-1 != $category){
			$where['category'] = array('EQ', $category);
		}
	
		//$list = $this->where($where)->limit($pageStart, $pageSize)->order('date(create_time) desc,weight desc,create_time desc')->select();
		/* $list = $this->where($where)->limit($pageStart, $pageSize)
				->order(
					'CASE WHEN refresh_time <> 0 THEN DATE_FORMAT(refresh_time, \'%y%m%d\') ELSE DATE_FORMAT(create_time, \'%y%m%d\') END DESC,
					weight desc,
					date(create_time) desc'
				)->select(); */
		$list = $this->where($where)->limit($pageStart, $pageSize)
		->order(
				'CASE WHEN refresh_time <> 0 THEN DATE_FORMAT(refresh_time, \'%y%m%d\') ELSE DATE_FORMAT(create_time, \'%y%m%d\') END DESC,
					weight desc,
					refresh_time desc,
					create_time desc
				'
				)->select();
		
		$new_data = array();
		foreach($list as $key=>$value){
			$user_model = new AdminUserModel();
			$nickname = $user_model->where('admin_id = '.$value['creator_id'])->getField('real_name');
			$company_id = $user_model->where('admin_id = '.$value['creator_id'])->getField('company_id');
			if($nickname){
				if($company_id){
					$company_model = M("vrnews1.company", null);
					$company_name = $company_model->where('company_id = '.$company_id)->getField('name');
					$list[$key]['creator_name'] = $company_name.":".$nickname;
				}else{
					$list[$key]['creator_name'] = $nickname;
				}
			}
			$new_data[] = $list[$key];
		}
		return $new_data;
	}
	
	public function queryLiveCount($status = -1, $name = null, $category = -1){
		$where = array();
		$where['is_fast'] = array('EQ', 0); //非快直播
// 		if(-1 != $status){
// 			$where['status'] = array('EQ', $status);
// 		}else {
// 			//2 为删除
// 			$where['status'] = array('NEQ', 0);
// 		}
// 		if($name && !empty($name)){
// 			$where['name'] = array('like','%'.$name.'%');
// 		}
	
// 		if(-1 != $category){
// 			$where['category'] = array('EQ', $category);
// 		}
		if(-1 != $status){
			//状态 1 正常 0 删除 2 直播结束 3 未开始 4 正在直播 5 直播回顾
			if(3 == $status){
				$where['status'] = array('EQ', 1);
				$where['start_time'] = array('GT', date('Y-m-d H:i:s'));
			}else if(2 == $status){
				$where['status'] = array('EQ', 2);
			}else if(4 == $status){
				$where['status'] = array('IN', array('1', '4'));
				$where['start_time'] = array('ELT', date('Y-m-d H:i:s'));
			}else if(5 == $status){
				$where['status'] = array('EQ', 5);
			}
		}else {
			//2 为删除
			$where['status'] = array('NEQ', 0);
		}
		if($name && !empty($name)){
			$where['name'] = array('like','%'.$name.'%');
		}
		$where['category'] = array('NEQ', 6);
		if(-1 != $category){
			$where['category'] = array('EQ', $category);
		}
		return  $this->where($where)->count();
	}
	
	public function update_live_category($live_id){
		$info = $this->find($live_id);
		if($info){
			if(!in_array($info['category'], array(3,4,5))){
				$sql = 'update vrlive.live set category=(SELECT case when count(a.camera_id) > 0 then 2 else '.$info['category'].' end
                        FROM vrlive.live_camera_angle a,vrlive.live_channel b
                   where a.source_id=b.channel_id and b.device_type=1
                    and a.status=1 and a.live_id='.$live_id.')
                 where live_id='.$live_id;
				$this->execute($sql);
			}
			
		}
		
	}
	
	public function updateLiveCount($live_id, $count){
// 		$ret = $this->where(array('live_id'=>$live_id))->setInc('play_count', $count);
		return $this->where(array('live_id'=>$live_id))->save(array('play_count'=>$count));
	}
	public function getNextSortNumber(){
		$sort_number = 0;
		$sql = 'select ifnull(max(sort_number),0)+1 as next_sort_number from vrlive.live_panel_manage';
		$list=$this->query($sql);
		if($list && !empty($list)){
			foreach($list as $key=>$value){
				$sort_number = $value['next_sort_number'];
				break;
			}
		}
		if (empty($sort_number)){
			$sort_number=1;
		}
		return $sort_number; 
	}
	
	public function getLievPanelById($msg_id,$opt_type){
		$res = array();
		$sql = "select * from vrlive.live_panel_manage where id=$msg_id";
		$list=$this->query($sql);		
		if($list && !empty($list)){
			foreach($list as $key=>$value){
				$res = $value;
				break;
			}
			if (!empty($res))
			{
			  $res['create_time'] = date("Y-m-d", strtotime($res['create_time']));
			  if (empty($res['user_speak_content'])){
			  	$res['user_speak_content'] = '';
			  }			  			  	
			  //$sql = "select * from vrlive.live_panel_Files where msg_id=$msg_id";			  
			  //$res2=$this->query($sql);
			  //$res['msg_files'] = $res2;
			  $res['opt_type'] = $opt_type;//用来表示当前是编辑，还是增加
			}
		}
		return $res;		
	}
	
	//获取直播员信息
	public function getCompere($live_id){
		$ret= array("creator_id"=>0,"live_man_alias"=>"","live_man_cate","live_man_avatar_url"=>"");
		$list= $this->where(array('live_id'=>$live_id))->select();
		if($list && !empty($list)){
			foreach($list as $key=>$value){
				$ret['creator_id'] = $value['creator_id'];
				$ret['live_man_cate'] = $value['live_man_cate'];
				$ret['live_man_alias'] = $value['live_man_alias'];
				$ret['live_man_avatar_url'] = $value['live_man_avatar_url'];				
				break;
			}
		}
		return  $ret;
	}
	
	//获取图文消息的图片集
	public function getLivePanelImages($live_id){
		$ret=array();
		$sql = "select file_url from vrlive.live_panel_images where live_id=$live_id";
		$list=$this->query($sql);
		if($list && !empty($list)){
			foreach($list as $key=>$value){
				$ret[] = $value['file_url'];
			}
		}
		return  $ret;
	}
	
	//获得图文消息的视频文件地址
	public function getLivePanelVideos($live_id){		
	}
	
	
	
	//获得上榜用户信息
	public function getToListUserInfo($data){
		$ret=array(
					"user_username"	=>$data['onlist_nickname'],
					"user_id"		=>$data['onlist_user_id'],
					"user_content"	=>$data['user_speak_content'],
					"msg_time"	=>date("H:i:s",strtotime($value['user_speak_time'])),
					"msg_date"	=>date("Y-m-d",strtotime($value['user_speak_time']))
				);
		return  $ret;
	}
	
	public function getDateTime($data){
		$date_time = '';
		if($data['msg_id']){
			$sql = "select create_time from vrlive.live_panel_manage where id=".$data['msg_id'];
			$data=$this->query($sql);
			if($data){
				foreach($data as $key=>$value){
					$date_time = $value['create_time'];
				}
			}
		}else{
			$date_time = date('Y-m-d H:i:s',time());
		}
		return $date_time;
	}
	
	
// 	//获得上榜用户信息
// 	public function getToListUserInfo($msg_id){
// 		$ret=array(/*"user_avatar"	=>"",
// 		"user_username"	=>"",
// 		"user_id"		=>"",
// 		"user_content"	=>"",
// 		"msg_time"	=>"",
// 		"msg_date"	=>""*/
// 		);
// 		$sql = "select u.avatar,u.nickname,u.user_id,m.user_speak_content,m.user_speak_time "
// 				."from vrlive.live_panel_manage as m left join vruser1.user as u "
// 				."on m.onlist_user_id=u.user_id "
// 						."where m.id=$msg_id and m.content_type=2";
// 						$list=$this->query($sql);
// 						if($list && !empty($list)){
// 							foreach($list as $key=>$value){
// 							$ret['user_avatar'] = $value['avatar'];					//"聊天室用户头像",
// 				$ret['user_username'] = $value['nickname'];	//"聊天室用户姓名"
// 				$ret['user_id'] = $value['user_id'];	//"聊天室用户ID"
// 				$ret['user_content'] = $value['user_speak_content'];	//"聊天室用户留言"
// 				$ret['msg_time'] = date("H:i:s",strtotime($value['user_speak_time']));		//"聊天室用户留言时间,如十二点零六：12:06:06"
// 				$ret['msg_date'] = date("Y-m-d",strtotime($value['user_speak_time']));		//"聊天室用户留言日期，如2016年12月22日：20161222"
// 					break;
// 	}
// 	}
// 	return  $ret;
// 		}
	
	public function Live_Update_Pic_Txt(&$data, $json_data = null){		
		$html_content = $data['content'];
		$onlist_user_id = $data['onlist_user_id'];
		if (empty($html_content)){
		  return array('code'=>0,'msg'=>'图文内容不能为空');
		}
		
		$live_id = $data['live_id'];
		$msg_id = $data['msg_id'];
		$opt_type = $data['opt_type'];//<!-- opt_type:1(浏览状态，新增状态）；2（编辑状态）；3：（上榜状态） -->
		$create_time = time();
		$create_time = date("Y-m-d H:i:s", $create_time);
		$update_time = $create_time;

		if($data['creator_id'] != 1) {
			//查看 缓存数据
			$redis = new Redis();
			$red_name = C('environment') . '_admin_role_' . $data['creator_id'];
			$key = $redis->buildKey($red_name);
			$red_list = $redis->get_redis($key);
			if (!$red_list) {
				//如 无缓存 查看数据
				$red_list = AdminbaseController::getAdminRole($data['creator_id']);
			} else {
				$red_list = $red_list[0];
			}

			$role_arr = i_array_column($red_list, "action_name");
		}

		
		//<!-- opt_type:1(浏览状态，新增状态,要上传非上榜的图文）；2（编辑状态:含正常数据的编辑，及上榜回复信息的编辑）；3：（上榜状态:要添加新的上榜图文）;4:表示是加载数据到图文消息 -->
		if ($opt_type==2)
		{	
			$sql = "update vrlive.live_panel_manage set pic_txt_content='".addslashes($this->userTextEncode($html_content))."', update_time='$update_time',json_data='".addslashes($json_data)."' "
                  ."where live_id='$live_id' and id='$msg_id'";
			$this->execute($sql);
			return array('code'=>200,'msg'=>'编辑成功','opt_type'=>$opt_type,'data'=>$this->getLievPanelById($msg_id,$opt_type));
		};
		
		if ($opt_type==1)
		{
			if($data['creator_id'] != 1) {
				//消息 判断是否有权限
				if (!in_array("快直播-高级管理-添加图文消息", $role_arr) && !in_array("快直播-图文直播-添加图文消息", $role_arr)) {
					return array('code' => 200, 'msg' => '暂无此权限', 'data' => array());
				}
			}

			$content_type = 1;
			$sort_number = $this->getNextSortNumber();
			$sql = "insert into vrlive.live_panel_manage(live_id,create_time,update_time,pic_txt_content,content_type,sort_number,creator_id,json_data) "
				  ."values('$live_id','$create_time','$update_time','".addslashes($this->userTextEncode($html_content))."',$content_type,$sort_number,'".$data['creator_id']."','".addslashes($json_data)."')";					
			$this->execute($sql);
			$msg_id = $this->getLastInsID();
			
			//$this->processVideoFiles($data);
			$data['msg_id']= $msg_id;
			return array('code'=>200,'msg'=>'保存成功','opt_type'=>$opt_type,'data'=>$this->getLievPanelById($msg_id,$opt_type));			
		}
		
		if ($opt_type==3)
		{
			if($data['creator_id'] != 1) {
				//上榜 判断是否有权限
				if (!in_array("快直播-高级管理-上榜聊天室消息", $role_arr) && !in_array("快直播-图文直播-上榜聊天室消息", $role_arr)) {
					return array('code' => 200, 'msg' => '暂无此权限', 'data' => array());
				}
			}
			$content_type = 2;
			$sort_number = $this->getNextSortNumber();
			$onlist_user_id = $data["onlist_user_id"];//上榜用户编号
			$onlist_nickname = $data["onlist_nickname"];//上榜用户昵称
			$user_speak_content = $data["user_speak_content"];//上榜用户发言
			$user_speak_time = $data["user_speak_time"];//上榜用户发言时间
			if (empty($user_speak_time)){
				$user_speak_time='0';
			}

			$sql = "insert into vrlive.live_panel_manage(live_id,create_time,update_time,pic_txt_content,content_type,onlist_user_id,onlist_nickname,user_speak_content,user_speak_time,sort_number,creator_id,json_data) "
					."values('$live_id','$create_time','$update_time','".addslashes($this->userTextEncode($html_content))."',$content_type,'$onlist_user_id','$onlist_nickname','".addslashes($user_speak_content)."','$user_speak_time',$sort_number,'".$data['creator_id']."','".addslashes($json_data)."')";
			$this->execute($sql);
			$msg_id = $this->getLastInsID();
			//$this->processVideoFiles($data);
			$data['msg_id']= $msg_id;
			return array('code'=>200,'msg'=>'上榜成功','data'=>$this->getLievPanelById($msg_id,$opt_type));
		}		
		return array('code'=>0,'msg'=>'未知操作类型','data'=>array());
	}
		
	public function processVideoFiles($data){
		foreach ($data['files'] as $key=>$value){
			$value['local_file_rece_dir']='local_file_rece_dir';
			$value['local_file_save_dir']='local_file_save_dir';
			$value['local_file_name']='local_file_name';
			$sql = "insert into vrlive.live_panel_files"
					."(live_id,msg_id,file_tag_id,client_file_dir,client_file_name,local_file_rece_dir,local_file_save_dir,local_file_name,file_flag) "
					."values('$live_id','$msg_id','{$value['id']}','".addslashes($value['dir'])."','".addslashes($value['file_name'])."',"
			  	    ."'".addslashes($value['local_file_rece_dir'])."','".addslashes($value['local_file_save_dir'])."','".addslashes($value['local_file_name'])."',0)";
			$this->execute($sql);
		}
	}
	
	/**
	 * 把用户输入的文本转义（主要针对特殊符号和emoji表情）
	 * @param $str
	 * @return json
	 */
	public function userTextEncode($str){
		if(!is_string($str))return $str;
		if(!$str || $str=='undefined')return '';
	
		$text = json_encode($str);
		$text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
			return addslashes($str[0]);
		},$text);
		return json_decode($text);
	}
}

